<template>
  <div>
    <el-form
      :model="queryForm"
      ref="queryForm"
      :inline="true"
      label-width="88px"
    >
      <el-form-item label="设备类型" prop="deviceType">
        <el-select
          v-model="queryForm.deviceType"
          clearable
          placeholder="请选择"
        >
          <el-option label="pos机" value="1"></el-option>
          <el-option label="双屏机" value="2"></el-option>
          <el-option label="小票机" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="密钥" prop="deviceSerialNum">
        <el-input
          v-model="queryForm.deviceSerialNum"
          placeholder="请输入设备密钥"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="设备编号" prop="likeDeviceNo">
        <el-input
          v-model="queryForm.likeDeviceNo"
          placeholder="请输入设备编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          type="info"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table :data="equipmentList">
      <af-table-column label="油站名称" align="left" prop="stationName" />
      <!--
    <af-table-column
      label="油站名称"
      align="left"
      prop="stationName"
      v-if="jiBie !== 2"
    />
    -->
      <af-table-column label="设备类型" align="left" prop="deviceType">
        <template slot-scope="scope">
          {{
            scope.row.deviceType == "1"
              ? "POS"
              : "" + scope.row.deviceType == "2"
              ? "双屏机"
              : "" + scope.row.deviceType == "3"
              ? "小票机"
              : ""
          }}
        </template>
      </af-table-column>

      <af-table-column label="设备类型" align="left" prop="printType">
        <template slot-scope="scope">
          {{
            scope.row.printType == "1"
              ? "顾客联"
              : "" + scope.row.printType == "2"
              ? "商户联"
              : "" + scope.row.printType == "3"
              ? "顾客+商户联"
              : ""
          }}
        </template>
      </af-table-column>
      <af-table-column label="设备编号" align="left" prop="deviceNo" />

      <af-table-column label="设备密钥" align="left" prop="deviceSerialNum">
        <!--
      <template slot-scope="scope">
        {{ scope.row.deviceType == "1" ? scope.row.deviceSerialNum : "无" }}
      </template>
      -->
      </af-table-column>
      <!--
    <af-table-column label="绑定油枪号" align="left" prop="gunNo" />
    -->
      <af-table-column label="设备厂家" align="left" prop="deviceFactory" />
      <af-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </af-table-column>
    </el-table>

    <pagination
      :hidden="total > 0 ? false : true"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
      :autoScroll="true"
    />

    <!-- 添加或修改油站设备管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      status-icon
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        :rules="rules"
        label-width="140px"
      >
        <!--
      :rules="{
        required: (form.userLevel==1 || form.userLevel==2),
        message: '请选择油企名称',
        trigger: 'change',
      }"
      :rules="{
        required: form.userLevel==2,
        message: '请选择油企名称',
        trigger: 'change',
      }"
    -->

        <el-form-item label="归属站点" prop="stationId">
          <el-select
            v-model="dialogForm.stationId"
            placeholder="请选择归属站点"
            size="small"
          >
            <el-option
              :label="ele.stationName"
              :value="+ele.stationId"
              v-for="ele in stationListOptions"
              :key="ele.stationId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备类型" prop="deviceType">
          <el-select
            v-model="dialogForm.deviceType"
            placeholder="请选择设备类型"
            clearable
            size="small"
          >
            <el-option label="POS" value="1"></el-option>
            <el-option label="双屏机" value="2"></el-option>
            <el-option label="小票机" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="打印小票类型"
          prop="printType"
          v-if="dialogForm.deviceType == 3"
        >
          <el-select
            v-model="dialogForm.printType"
            placeholder="请选择小票类型"
            clearable
            size="small"
          >
            <el-option label="顾客联" value="1"></el-option>
            <el-option label="商户联" value="2"></el-option>
            <el-option label="顾客+商户联" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="使用该Pos的员工" prop="userIdList">
          <template v-if="personnelList.length === 0">
            {{ "木有拉取到员工，请先配置员工" }}
          </template>
          <template v-else>
            <el-checkbox-group v-model="dialogForm.userIdList">
              <el-checkbox
                v-for="item in personnelList"
                :key="item.userId"
                :label="'' + item.userId"
              >
                {{ item.nickName + "-" + item.userName }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </el-form-item>

        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="dialogForm.deviceName"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input
            v-model="dialogForm.deviceNo"
            placeholder="请输入设备编号"
            @input="deviceNoInput"
          />
        </el-form-item>
        <el-form-item label="密钥" prop="deviceSerialNum">
          <el-input
            v-model="dialogForm.deviceSerialNum"
            placeholder="请输入设备密钥"
          />
        </el-form-item>
        <!--
      <el-form-item label="绑定油枪号" prop="checkedGunList" required>
        <template v-if="allGunList.length === 0">
          请先在油枪管理里配置油枪
        </template>
        <template v-else>
          <el-checkbox-group
            v-model="dialogForm.checkedGunList"
            v-if="dialogForm.deviceType == 2"
          >
            <el-checkbox
              v-for="item in posList"
              :key="item.oilGunId"
              :label="item.oilGunNo"
              :value="item.oilGunNo"
            >
              {{ item.oilGunNo + "号枪/" + item.oilName }}
            </el-checkbox>
          </el-checkbox-group>

          <el-checkbox-group
            v-model="dialogForm.checkedGunList"
            v-if="dialogForm.deviceType == 1"
          >
            <el-checkbox
              v-for="item in printList"
              :key="item.oilGunId"
              :label="item.oilGunNo"
              :value="item.oilGunNo"
            >
              {{ item.oilGunNo + "号枪/" + item.oilName }}
            </el-checkbox>
          </el-checkbox-group>
        </template>
      </el-form-item>
      -->
        <el-form-item label="设备厂家" prop="deviceFactory">
          <el-input
            v-model="dialogForm.deviceFactory"
            placeholder="请输入设备厂家"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listManage,
  getManage,
  delManage,
  addManage,
  updateManage,
  exportManage,
  changeManageStatus,
} from "@/api/station/manage";
import { listPersonnel } from "@/api/station/personnel";

import { getEnterpriseList, getStationList } from "@/api/dept";

export default {
  name: "Station_Equipment",
  data() {
    let validateGunNo = (rule, value, callback) => {
      if (this.allGunList.length === 0) {
        callback(new Error("请先配置油枪后再来配置设备"));
        return;
      }
      if (this.dialogForm.checkedGunList.length === 0) {
        callback(new Error("请勾选要绑定的油枪"));
        return;
      }
      callback();
    };
    return {
      pageStatus: 0,
      // 油站设备管理表格数据
      equipmentList: [],
      // 油枪复选
      allGunList: [],
      // 已选的油枪
      checkedGunList: [],
      //设备状态
      stationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 总条数
      total: 100,
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10, // 初始值只能比10大
        deviceNo: null,
        deviceSerialNum: null, // 设备密钥
        likeDeviceNo: null,
      },
      // 弹窗表单参数
      dialogForm: {
        checkedGunList: [],
        deviceStatus: "1",
        deviceType: "1",
        enterpriseId: "",
        stationId: "",
        userIdList: [],
      },
      currentList: [],
      // 表单校验
      rules: {
        deviceNo: [
          { required: true, message: "请输入设备编号", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "请输入设备名", trigger: "blur" },
        ],
        // deviceSerialNum: [
        //   { required: true, message: "请输入设备密钥", trigger: "blur" },
        // ],
        deviceType: [
          { required: true, message: "请选择设备类型", trigger: "blur" },
        ],
        checkedGunList: [{ validator: validateGunNo, trigger: "change" }],
        deviceStatus: [
          { required: true, message: "请选择设备状态", trigger: "blur" },
        ],
        deviceFactory: [
          // { required: true, message: '请输入设备厂家', trigger: 'blur' }
        ],
      },
      updateAble: false,
      deviceTypeAble: false,
      groupListOptions: [],
      stationListOptions: [],
      personnelList: [],
    };
  },
  created() {
    // console.log('2222====',this.userLevel);
    // console.log('22222',this.presentEnterprise);
    this.init();
    this.setPageStatus();
    this.getStationList();
    this.getPersonnelList();
  },
  computed: {
    // posList() {
    //   // 排除其他pos已经添加过的
    //   const temp = this.allGunList.filter((item) => {
    //     let flag = false;
    //     this.equipmentList.map((ele) => {
    //       if (ele.deviceType == 2) {
    //         if (ele.gunNo.split(",").includes(item.oilGunNo)) {
    //           flag = true;
    //           return;
    //         }
    //       }
    //     });
    //     return flag;
    //   });
    //   // 查找自己的
    //   const temp2 = this.allGunList.filter((item) => {
    //     let flag = true;
    //     temp.map((ele) => {
    //       if (item.oilGunNo == ele.oilGunNo) {
    //         flag = false;
    //       }
    //     });
    //     return flag;
    //   });
    //   return this.currentList.concat(temp2);
    // },
    // printList() {
    //   const temp = this.allGunList.filter((item) => {
    //     let flag = false;
    //     this.equipmentList.map((ele) => {
    //       if (ele.deviceType == 1) {
    //         if (ele.gunNo.split(",").includes(item.oilGunNo)) {
    //           flag = true;
    //           return;
    //         }
    //       }
    //     });
    //     return flag;
    //   });
    //   const temp2 = this.allGunList.filter((item) => {
    //     let flag = true;
    //     temp.map((ele) => {
    //       if (item.oilGunNo == ele.oilGunNo) {
    //         flag = false;
    //       }
    //     });
    //     return flag;
    //   });
    //   return this.currentList.concat(temp2);
    // },
  },
  methods: {
    getPersonnelList() {
      listPersonnel({
        pageNum: 1,
        pageSize: 1000,
        personnelPhone: null,
        enterpriseId: this.presentEnterprise.enterpriseId,
        userLevel: "2",
      }).then((response) => {
        this.personnelList = response.rows;
      });
    },
    getStationList() {
      getStationList({
        pageSize: 10000,
        pageNum: 1,
        enterpriseId: this.presentEnterprise.enterpriseId,
      })
        .then((res) => {
          this.stationListOptions = res.rows;
        })
        .catch((err) => {});
    },
    init() {
      this.getList();
    },
    setPageStatus() {
      this.queryPageStatus([2]).then((res) => {
        this.pageStatus = res;
      });
    },
    /** 查询油站设备管理列表 首页表单 */
    getList() {
      listManage(this.queryForm).then((response) => {
        this.equipmentList = response.rows;
        this.total = response.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },
    deviceNoInput(value) {
      this.dialogForm.posQueue = value;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.updateAble = false;
      this.currentList = [];
      this.title = "添加油站设备管理";
      this.dialogForm = {
        checkedGunList: [],
        deviceStatus: "1",
        deviceType: "1",
        posFanoutExchange: "posFanoutExchange-" + this.deptId,
        userIdList: [],
      };
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 查找自己已经选中的枪号
      this.updateAble = true;
      this.currentList = this.allGunList.filter((ele) => {
        return row.gunNo.split(",").includes(ele.oilGunNo);
      });
      let checkedGunList;
      // 将自己有的抢号 默认勾选
      if (Object.prototype.toString.call(row.gunNo) === "[object String]") {
        checkedGunList = [...new Set(row.gunNo.split(","))].filter((ele) => {
          return ele.toString().trim() !== "";
        });
      } else {
        checkedGunList = [];
      }
      if (!row.userIdList) {
        row.userIdList = [];
      }
      this.dialogForm = { ...row, checkedGunList };

      this.title = "修改油站设备管理";
      this.open = true;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          //this.dialogForm.gunNo = this.dialogForm.checkedGunList.toString();
          let list = [];
          for (let i = 0; i < this.dialogForm.checkedGunList.length; i++) {
            for (let j = 0; j < this.allGunList.length; j++) {
              if (
                this.dialogForm.checkedGunList[i] == this.allGunList[j].oilGunNo
              ) {
                list.push(this.allGunList[j].oilGunNo);
              }
            }
          }
          this.dialogForm.gunNo = list.toString();
          if (this.dialogForm.deviceId != null) {
            updateManage(this.dialogForm).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addManage(this.dialogForm).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId;
      this.$confirm("是否确认删除油站设备管理", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delManage(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    comDeviceType(val) {
      // 每个油站只能有一种设备，以第一次添加的设备为准
      if (this.equipmentList.length == 0) {
        this.deviceTypeAble = false;
        return true;
      }
      this.dialogForm.deviceType = this.equipmentList[0].deviceType;
      this.deviceTypeAble = true;
      return this.equipmentList[0].deviceType == val;
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   const queryForm = this.queryForm;
    //   this.$confirm("是否确认导出所有油站设备管理数据项?", "警告", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(function () {
    //       return exportManage(queryForm);
    //     })
    //     .then((response) => {
    //       this.download(response.msg);
    //     });
    // },
  },
};
</script>
